<template>
  <a-drawer v-model:visible="visible" title="接口批量分类" placement="right" :closable="false" :after-visible-change="afterVisibleChange">
    <p>接口名称：{{ selectList }}</p>
    接口分类： <a-input-search v-model:value="searchValue" style="margin-bottom: 8px" placeholder="Search" />
    <div class="tree">
      <a-tree :expanded-keys="expandedKeys" :auto-expand-parent="autoExpandParent" :tree-data="treeData" @expand="onExpand" @select="onSelect">
        <template #title="{ dirName }">
          <span v-if="dirName.indexOf(searchValue) > -1">
            {{ dirName.substr(0, dirName.indexOf(searchValue)) }}
            <span style="color: #f50">{{ searchValue }}</span>
            {{ dirName.substr(dirName.indexOf(searchValue) + searchValue.length) }}
          </span>
          <span v-else>{{ dirName }}</span>
        </template>
      </a-tree>
    </div>
    <a-button style="margin-right: 8px" @click="onClose">取消</a-button>
    <a-button type="primary" @click="onSubmit">确定</a-button>
  </a-drawer>
</template>
<script setup lang="ts">
  import { message } from 'ant-design-vue';
  import { ref, watch, defineEmits, Ref } from 'vue';
  import { DataTree } from '../type/index';
  import { getinterFace, editBatchClassify } from '@/api/test/interFace';
  import { TreeDataItem } from 'ant-design-vue/es/tree/Tree';
  //弹窗控制
  const visible = ref<boolean>(false);
  const afterVisibleChange = (_bool: boolean) => {
    visible.value = true;
    autoExpandParent.value = true;
  };
  //接收父组件数据
  const props = defineProps({
    selectList: {
      type: String,
      default: () => {
        return;
      },
    },
    selectedRowKeys1: {
      type: Array,
      default: () => {
        return;
      },
    },
  });
  // 打开弹窗，数据变化，请求接口
  let listId = ref();
  watch(
    () => props.selectedRowKeys1,
    nval => {
      if (nval) {
        listId.value = nval;
      }
    },
  );

  //选中的数据
  let Newdata = ref();
  let id = ref();
  const emit = defineEmits(['clickNew', 'changeShowDir']);
  const onSelect = (dirId: number, data: Object, _event: any) => {
    console.log('Trigger Select', dirId, '--', data);
    Newdata.value = data.node;
    searchValue.value = data.node.dirName;
    id.value = data.node.dirId;
  };

  const onSubmit = () => {
    if (searchValue.value != '') {
      emit('clickNew', Newdata);
      emit('changeShowDir', 'false');
      visible.value = false;
      //接口
      let data = {
        newDirId: id.value,
        portsIdList: listId.value,
      };
      //接口
      editBatchClassify(data).then((res: any) => {
        if (res.code == 100200) {
          message.success(res.msg);
        } else {
          message.error(res.msg);
        }
        console.log(res);
      });
    } else {
      alert('请选择正确的分类名称！');
    }
  };
  const onClose = () => {
    visible.value = false;
    emit('changeShowDir', 'false');
  };

  //树形结构
  const x = 3;
  const y = 2;
  const z = 1;
  const genData: TreeDataItem[] = [];
  const treeData = ref<TreeDataItem[]>(genData);
  //分类接口
  //   const treeData = ref<DataTree[]>([]);
  getinterFace().then((res: { data: any }) => {
    treeData.value = res.data;
  });

  const generateData = (_level: number, _preKey?: string, _tns?: TreeDataItem[]) => {
    const preKey = _preKey || '0';
    const tns = _tns || genData;

    const children = [];
    for (let i = 0; i < x; i++) {
      const key = `${preKey}-${i}`;
      tns.push({ dirName: key, key });
      if (i < y) {
        children.push(key);
      }
    }
    if (_level < 0) {
      return tns;
    }
    const level = _level - 1;
    children.forEach((key, index) => {
      tns[index].children = [];
      return generateData(level, key, tns[index].children);
    });
  };
  generateData(z);

  const dataList: TreeDataItem[] = [];
  const generateList = (data: TreeDataItem[]) => {
    for (let i = 0; i < data.length; i++) {
      const node = data[i];
      const key = node.key;
      dataList.push({ key, dirName: key as string });
      if (node.children) {
        generateList(node.children);
      }
    }
  };
  generateList(genData);

  const getParentKey = (key: string, tree: TreeDataItem[]): string | number | undefined => {
    let parentKey;
    for (let i = 0; i < tree.length; i++) {
      const node = tree[i];
      if (node.children) {
        if (node.children.some(item => item.key === key)) {
          parentKey = node.key;
        } else if (getParentKey(key, node.children)) {
          parentKey = getParentKey(key, node.children);
        }
      }
    }
    return parentKey;
  };

  const expandedKeys = ref<string[]>([]);
  const searchValue = ref<string>('');
  const autoExpandParent = ref<boolean>(true);
  // const gData = ref<TreeDataItem[]>(genData);
  const onExpand = (keys: string[]) => {
    expandedKeys.value = keys;
    autoExpandParent.value = false;
    console.log(expandedKeys.value, 'key');
  };

  watch(searchValue, value => {
    const expanded = dataList
      .map((item: TreeDataItem) => {
        if ((item.dirName as string).indexOf(value) > -1) {
          return getParentKey(item.key as string, treeData.value);
        }
        return null;
      })
      .filter((item, i, self) => item && self.indexOf(item) === i);
    expandedKeys.value = expanded as string[];
    searchValue.value = value;
    autoExpandParent.value = true;
  });
</script>
<style lang="less" scoped>
  .tree {
    border: 1px solid rgb(230, 224, 224);
    width: 100%;
    height: 70%;
  }
</style>
